package com.lyh.hkcloud.module.m1300030;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.*;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.activity.HomeActivity;
import com.lyh.hkcloud.base.BaseActivity;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.m1300030.adapter.ListViewAdapter;
import com.lyh.hkcloud.module.m1300030.service.Service;
import com.lyh.hkcloud.util.base.JsonUtil;
import com.lyh.hkcloud.util.base.LoadingUtils;
import com.lyh.hkcloud.util.base.StringUtils;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * @author: zhongfan
 * @program: hkCloud
 * @description: 出入场登记列表
 * @company—date: 利元数据 2022-02-11 16:28
 **/
public class IndexActivity extends BaseActivity implements  View.OnClickListener, DatePicker.OnDateChangedListener, TimePicker.OnTimeChangedListener{

    private ImageView goBack;
    private Button btReceiver;
    private Button btResetting;
    private EditText etDocumentNo;
    private TextView tvCreationDate;

    private Service service;

    private ListView lvAssets;
    private List<Map<String,Object>> dataMap = new ArrayList<>();
    private ListViewAdapter listViewAdapter;
    private Integer receiverFocusEvent = 0;

    private int year, month, day, hour, minute;
    private StringBuffer date, time;

    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected int getSubmitResId() {
        return R.id.bt_receiver;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_1300030;
    }

    @Override
    protected int getClearResId() {
        return R.id.bt_resetting;
    }

    @Override
    protected void onBeginInit() {
        service = new Service(IndexActivity.this);
    }

    @Override
    protected void initView() {
        goBack = findViewById(R.id.go_back);
        btReceiver = findViewById(R.id.bt_receiver);
        btResetting = findViewById(R.id.bt_resetting);
        lvAssets = findViewById(R.id.lv_assets);
        etDocumentNo = findViewById(R.id.et_document_no);
        tvCreationDate = findViewById(R.id.tv_date);

        goBack.setOnClickListener(this);
        etDocumentNo.setOnClickListener(this);
        tvCreationDate.setOnClickListener(this);
        getSupportActionBar().hide();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listViewAdapter = new ListViewAdapter(this, dataMap, IndexActivity.this);
        lvAssets.setAdapter(listViewAdapter);
        lvAssets.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String,Object>data=dataMap.get(position);
                Intent intent =new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300087.IndexActivity.class);
                intent.putExtra(BusinessConstants.BILL_NUMBER,data.get(BusinessConstants.BILL_NUMBER).toString());
                IndexActivity.this.startActivity(intent);
            }
        });
        date = new StringBuffer();
        time = new StringBuffer();
//        initView();
        initDateTime();
        QueryRegistrationInformation();
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

        System.out.println("年："+year+"；月："+monthOfYear+"；日："+dayOfMonth);

        this.year = year;
        this.month = monthOfYear + 1;
        this.day = dayOfMonth;
    }

    @Override
    protected void initEvent() {
        etDocumentNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    if (BusinessConstants.ENTER_DOCUMENT_NUMBER.equals(etDocumentNo.getText().toString())) {
                        etDocumentNo.setText("");
                    }
                    receiverFocusEvent = 1;
                }else{
                    if ( etDocumentNo.getText() == null || "".equals(etDocumentNo.getText().toString())) {
                        etDocumentNo.setText(BusinessConstants.ENTER_DOCUMENT_NUMBER);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });
    }

    private void initDateTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        Log.v("当前月份---",String.valueOf( calendar.get(Calendar.MONTH)));
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
        hour = calendar.get(Calendar.HOUR);
        minute = calendar.get(Calendar.MINUTE);
    }

    @Override
    protected void onSubmit() {
        btReceiver.setEnabled(false);
        showProgressDialog("提示", "提交中...");
        dataMap.clear();
        QueryRegistrationInformation();
        btReceiver.setEnabled(true);
        hideProgressDialog();
    }

    /**
     * 查询出入场登记列表
     * @param
     * @return void
     * @author: zhongfan
     * @Date 2022/2/27 19:54
    **/
    public void QueryRegistrationInformation(){
        Map<String, Object> objectMap = new HashMap<>();
        if (!"请输入单据编号".equals(etDocumentNo.getText().toString()) && StringUtils.isNotEmpty(etDocumentNo.getText().toString())) {
            objectMap.put("billnumber",etDocumentNo.getText().toString());
        }
        if (!"请选择日期".equals(tvCreationDate.getText().toString()) && StringUtils.isNotEmpty(tvCreationDate.getText().toString())) {
            objectMap.put("createdate",tvCreationDate.getText().toString()+" 00:00:00");
            objectMap.put("endcreatedate",tvCreationDate.getText().toString()+" 23:59:59");
        }

        service.post(JsonUtil.toJSONObject(objectMap), HttpUrlComstants.QUERY_REGISTRATION_INFORMATION, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                try {
                    JSONArray farecordlist = JsonUtil.getJsonObjectArray(response, "farecordlist", IndexActivity.this);
                    if (farecordlist == null || farecordlist.length() == 0) {
                        Toast.makeText(IndexActivity.this,"查询信息为空",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    for (int i = 0; i < farecordlist.length(); i++) {
                        Map<String, Object> recordMap = new HashMap<>();
                        recordMap.put("billnumber",farecordlist.getJSONObject(i).getString("billnumber"));
                        recordMap.put("psnname",farecordlist.getJSONObject(i).getString("psnname"));
                        recordMap.put("createtime",farecordlist.getJSONObject(i).getString("createtime"));
                        dataMap.add(recordMap);
                    }
                    //通知ListView更改数据源
                    if (listViewAdapter != null) {
                        listViewAdapter.notifyDataSetChanged();
                    } else {
                        listViewAdapter = new ListViewAdapter(IndexActivity.this, dataMap, IndexActivity.this);
                        lvAssets.setAdapter(listViewAdapter);
                    }
//                    lvAssets.setSelection(dataMap.size() - 1);//设置显示列表的最后一项

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
                LoadingUtils.getInstance(IndexActivity.this).hide();
            }
        });
    }

    private ProgressDialog progressDialog;

    /**
     * 提示加载
     */
    public  void showProgressDialog(String title, String message) {
        if (progressDialog == null) {

            progressDialog = ProgressDialog.show(IndexActivity.this, title, message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }

        progressDialog.show();

    }

    /**
     * 隐藏提示加载
     */
    public void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_back:
                    Intent intent = new Intent(IndexActivity.this, HomeActivity.class);
                    IndexActivity.this.startActivity(intent);
                break;
            case R.id.et_receiver:

                break;
            case R.id.tv_date:
                AlertDialog.Builder builder = new AlertDialog.Builder(IndexActivity.this);
                builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (date.length() > 0) { //清除上次记录的日期
                            date.delete(0, date.length());
                        }
                        tvCreationDate.setText(date.append(year).append("-").append(month).append("-").append(day).append(""));
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setNeutralButton("清空", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tvCreationDate.setText("");
                        dialog.dismiss();
                    }
                });
                final AlertDialog dialog = builder.create();
                View dialogView = View.inflate(IndexActivity.this, R.layout.dialog_date, null);
                final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker);

                dialog.setTitle("设置日期");
                dialog.setView(dialogView);
                dialog.show();
                //初始化日期监听事件
                datePicker.init(year, month - 1, day, this);
                break;
        }
    }

    /**
     * 时间改变的监听事件
     *
     * @param view
     * @param hourOfDay
     * @param minute
     */
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        this.hour = hourOfDay;
        this.minute = minute;
    }

}

